package com.wch.serverdemo.redis.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.wch.serverdemo.redis.IRedisDao;

@Service
public class RedisDaoImpl implements IRedisDao {

	
	@Autowired
	@Qualifier("redisTemplate")
	protected StringRedisTemplate redisTemplate;
	
	private String pre_key="jx_app_";
	
	@Override
	public void saveInfo(final String key, final String value) { 
		// TODO Auto-generated method stub
		final String saveKey = pre_key+key;
		redisTemplate.execute(new RedisCallback<Object>() {

			@Override
			public Object doInRedis(RedisConnection con)
					throws DataAccessException {
				con.set(redisTemplate.getStringSerializer().serialize(saveKey), redisTemplate.getStringSerializer().serialize(value));
				return null;
			}
		});
	}

	
	@Override
	public String getInfo(String key) {
		final String saveKey = pre_key+key;
		return redisTemplate.execute(new RedisCallback<String>() {

			@Override
			public String doInRedis(RedisConnection con) throws DataAccessException {
				byte[] bs = redisTemplate.getStringSerializer().serialize(saveKey);
				if(con.exists(bs)){
					byte[] bs2 = con.get(bs);
					String value = redisTemplate.getStringSerializer().deserialize(bs2);
					return value;
				}
				
				return null;
			}
		});
	}

}
